#Megalithic logging module
#Used for chat but also for system debug logging
#Each message has an origin, a destination, and a set of types
#Can search for specifics
#Example
#print logs.search(types=["chat","world"])
#   {"from":"system","to":"any","types":["chat","world","debug"],"message":"Server is going down soon"}
#   {"from":"joe","to":"any","types":["chat","world"],"message":"Aw, I was just starting to have fun"}
#   {"from":"sam","to":"joe","types":["chat","world"],"message":"If you whine, people will know your a whiner"}
import time

class MessageLog(object):
    def __init__(self,max_messages=None,mirror=None):
        self.messages = []
        self.max_messages = max_messages
        self.mirror = mirror
    def log(self,source="",destination="",types=[],message=[],orig_time=None,**kwargs):
        m = {"source":source,"destination":destination,
            "types":types,"message":message,"orig_time":orig_time,
            "recv_time":time.time()}
        self.messages.append(m)
        if self.max_messages and len(self.messages)>self.max_messages:
            del self.messages[0]
        if self.mirror and destination!="debug":
            self.mirror(m)
        return m
    def get_messages(self,source=None,destination=None,types=None):
        for m in self.messages:
            y = True
            if source and m["source"] != source:
                y = False
            if destination and m["destination"] != destination:
                y = False
            if types:
                tt = False
                for t in types:
                    if t in types:
                        tt = True
                if not tt:
                    y = False
            if y:
                yield m
    def user_chat(self,ukey,message,channel="world"):
        self.log(source=ukey,destination=channel,message=message,types=["chat"])
    def user_private(self,ukey,message,tkey):
        self.log(source=ukey,destination=tkey,message=message,types=["chat","private"])
    def system_message(self,msg,ukey):
        self.log(source="system",destination=ukey,message=msg,types=["info"])
    def system_announce(self,msg,channel="world"):
        self.log(source="system",destination=channel,message=msg,types=["info"])
    def debug(self,msg):
        self.log(source="system",destination="debug",message=msg,types=["debug"])
    def format(self,m):
        """Format a message and return the string, overwrite to include more info
        Default formatting is just a string representation of the message dictionary"""
        return str(m)

class PrintMessageLog(MessageLog):
    def __init__(self,*args,**kwargs):
        kwargs["max_messages"] = 1
        super(PrintMessageLog,self).__init__(*args,**kwargs)
    def log(self,*args,**kwargs):
        super(PrintMessageLog,self).log(*args,**kwargs)
        print self.format(self.messages[-1])
    def format(self,m):
        return m["message"]